package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class GetRSS implements Runnable {

    private long pid;
    private long rss = 0;
    private long limitMemory;
    private Thread thread;
    private JudgeSubject judgeSubject;

    public void setPid(long pid) {
        this.pid = pid;
    }

    public long getRss() {
        return rss;
    }

    public void setLimitMemory(long limitMemory) {
        this.limitMemory = limitMemory;
    }

    public void setThread(Thread thread) {
        this.thread = thread;
    }

    public void setJudgeSubject(JudgeSubject judgeSubject) {
        this.judgeSubject = judgeSubject;
    }

    @Override
    public void run() {
        Runtime runtime = Runtime.getRuntime();
        int state;
        long temp;
        while (true) {
            try {
                Process process = runtime.exec(new String[]{"ps", "-p", String.valueOf(pid), "-o", "rss"});
                state = process.waitFor();
                if (state != 0) {
                    break;
                }
                InputStream test = process.getInputStream();
                InputStreamReader testInputStreamReader = new InputStreamReader(test);
                BufferedReader testBufferedReader = new BufferedReader(testInputStreamReader);
                testBufferedReader.readLine();
                temp = Long.parseLong(testBufferedReader.readLine().trim());
                rss = Math.max(rss, temp);
                if (rss > limitMemory && thread.isAlive()) {
                    System.out.println(limitMemory+" "+rss);
                    judgeSubject.setResult("Memory Limit Exceeded");
                    thread.stop();
                    break;
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
